/**********************************************************************
* <pre>
* FILE : OrderDeliveryCommand.java
* CLASS : OrderDeliveryCommand
* AUTHOR : 
* FUNCTION : 订单发运
*======================================================================
* CHANGE HISTORY LOG
*----------------------------------------------------------------------
* MOD. NO.|   DATE   |    NAME    | REASON  |  CHANGE REQ.
*----------------------------------------------------------------------
*         |2010-05-25|            | Created |
* DESCRIPTION:
* </pre>
***********************************************************************/
package com.infodms.dms.actions.sales.ordermanage.delivery;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.swing.text.Utilities;

import org.apache.log4j.Logger;

import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.Utility;
import com.infodms.dms.common.getCompanyId.GetOemcompanyId;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.sales.financemanage.AccountBalanceDetailDao;
import com.infodms.dms.dao.sales.ordermanage.audit.OrderAuditDao;
import com.infodms.dms.dao.sales.ordermanage.delivery.OrderDeliveryDao;
import com.infodms.dms.dao.sales.ordermanage.orderreport.OrderReportDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TmBusinessAreaPO;
import com.infodms.dms.po.TtVsDlvryDtlPO;
import com.infodms.dms.po.TtVsDlvryPO;
import com.infodms.dms.po.TtVsDlvryReqDtlPO;
import com.infodms.dms.po.TtVsDlvryReqPO;
import com.infodms.dms.po.TtVsOrderDetailPO;
import com.infodms.dms.po.TtVsOrderPO;
import com.infodms.dms.po.TtVsOrderResourceReservePO;
import com.infodms.dms.po.TtVsReqCheckPO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.businessUtil.ReqLogUtil;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.po3.bean.PO;
import com.infoservice.po3.bean.PageResult;
import static com.infodms.dms.actions.sales.financemanage.AccountOpera.* ;

/**
 * @Title: 
 * @Description:InfoFrame3.0.V01
 * @Copyright: Copyright (c) 2010
 * @Company: www.infoservice.com.cn
 * @Date: 2010-5-25
 * @author 
 * @mail   
 * @version 1.0
 * @remark 发运指令下达
 */
public class OrderDeliveryCommand {
	
	public Logger logger = Logger.getLogger(DeliveryApply.class);   
	OrderDeliveryDao dao  = OrderDeliveryDao.getInstance();
	private final AccountBalanceDetailDao accoutDao = AccountBalanceDetailDao.getInstance();
	private ActionContext act = ActionContext.getContext();
	RequestWrapper request = act.getRequest();
	private final String deinitMyOneUrl = "/jsp/sales/ordermanage/delivery/orderResourse.jsp";
	private final String initUrl = "/jsp/sales/ordermanage/delivery/orderDeliveryCommand.jsp";
	private final String deinitUrl = "/jsp/sales/ordermanage/delivery/dealerOrderDelivery.jsp";
	private final String initList = "/jsp/sales/ordermanage/delivery/orderDeliveryDetail.jsp";
	private final String deinitList = "/jsp/sales/ordermanage/delivery/dealerOrderDeliveryDetail.jsp";
	private final String deinitList2 = "/jsp/sales/ordermanage/delivery/dealerOrderDeliveryDetail2.jsp";
	private final String queryBatchNumberInitURL = "/jsp/sales/ordermanage/delivery/queryBatchNumberInit.jsp";
	//private final String initDo = "/sales/ordermanage/delivery/OrderDeliveryCommand/deliveryQueryInit.do";
	private final OrderReportDao reportDao = OrderReportDao.getInstance();
	/**
	 * 发运指令下达页面初始化
	 */
	public void deliveryQueryInit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			List<Map<String, Object>> areaBusList=MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
			List<Map<String, Object>> orgIdList = reportDao.getTMOREG();
			act.setOutData("orgIdList", orgIdList);
		    act.setOutData("areaBusList", areaBusList);
			act.setForword(initUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"发运指令下达页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 发运指令下达查询
	 */
	public void deliveryQuery(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String startYear =request.getParamValue("startYear");			//订单起始年
			String endYear =request.getParamValue("endYear");				//订单结束年
			String startWeek = request.getParamValue("startWeek");			//订单起始周
			String endWeek = request.getParamValue("endWeek");				//订单结束周
			String orgId = request.getParamValue("orgId");	//大区ID
			String orderType = request.getParamValue("orderType");			//订单类型
			String areaId = CommonUtils.checkNull(request.getParamValue("areaId"));	//业务范围
			String transportType = request.getParamValue("transportType");	//发运方式
			//String groupCode = request.getParamValue("groupCode");		//物料组CODE
			//String materialCode = request.getParamValue("materialCode");	//物料CODE
			String dealerCode = CommonUtils.checkNull(request.getParamValue("dealerCode"));//经销商CODE
			String orderNo =request.getParamValue("orderNo");				//订单号码
			
			StringBuffer areaIds = new StringBuffer();
			List<Map<String, Object>> areaBusList=MaterialGroupManagerDao.getPoseIdBusiness(logonUser.getPoseId().toString());
			for (int i = 0; i < areaBusList.size(); i++) {
				if (!"".equals(String.valueOf(areaBusList.get(i).get("AREA_ID")))) {
					areaIds.append(String.valueOf(areaBusList.get(i).get("AREA_ID")));
				}
				if (i<areaBusList.size()-1) {
					areaIds.append(",");
				}
			}
			if(!dealerCode.equals("")){//截串加单引号
				String[] supp = dealerCode.split(",");
				dealerCode = "";
				for(int i=0;i<supp.length;i++){
					supp[i] = "'"+supp[i]+"'";
					if(!dealerCode.equals("")){
						dealerCode += "," + supp[i];
					}else{
						dealerCode = supp[i];
					}
				}
			}
			Long companyId = GetOemcompanyId.getOemCompanyId(logonUser);
			
			Integer curPage = request.getParamValue("curPage") !=null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps = dao.getDeliveryList(areaIds.toString(), orgId,startYear, startWeek, endYear, endWeek, orderType, areaId, dealerCode, transportType, orderNo, companyId,curPage, Constant.PAGE_SIZE);
			act.setOutData("ps", ps);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"发运指令下达查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 发运指令下达明细页面初始化
	 */
	public void deliveryToQueryInit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String reqId = request.getParamValue("reqId");
			String orderType = request.getParamValue("orderType");
			Long companyId = GetOemcompanyId.getOemCompanyId(logonUser);
			
			Map<String, Object> map = dao.getdeliveryMap(reqId);
			String areaGet = ((BigDecimal) map.get("AREA_ID")).toString();
			
			TmBusinessAreaPO areaPO = new TmBusinessAreaPO();
			areaPO.setAreaId(new Long(areaGet));
			List<PO> areaList = dao.select(areaPO);
			Long erpCode = null;
			if(areaList.size() != 0){
				areaPO = (TmBusinessAreaPO)areaList.get(0);
				erpCode = areaPO.getErpCode();
			}
			
			OrderAuditDao od = new OrderAuditDao();
			List<Map<String, Object>> list = dao.getorderResourceReserveDetailList(reqId,orderType,String.valueOf(companyId),erpCode.toString());
			BigDecimal dealerId = (BigDecimal)map.get("BILLING_ORG_ID");
			List<Map<String,Object>> discountList = accoutDao.getDiscountAccountInfoByDealerId(dealerId.toString());
			act.setOutData("map", map);
			act.setOutData("list", list);
			act.setOutData("discountList", discountList);
			act.setForword(initList);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"发运指令下达明细页面初始化");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 批次号选择
	 */
	public void patchNoSelect() {
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			String wareHouseId = CommonUtils.checkNull(request.getParamValue("wareHouseId"));// 仓库id
			String materalId = CommonUtils.checkNull(request.getParamValue("materalId")); // 订单数量
			String batchNo = CommonUtils.checkNull(request.getParamValue("batchNo")); // 物料id
			String amount = CommonUtils.checkNull(request.getParamValue("amount")); // 已配车数量
			String orderType = CommonUtils.checkNull(request.getParamValue("orderType")); // 订单类型
			String specialBatchNo = CommonUtils.checkNull(request.getParamValue("specialBatchNo")); // 特殊批次号
			String initNo = CommonUtils.checkNull(request.getParamValue("initNo")); // 初始批次
			String reqAmount = CommonUtils.checkNull(request.getParamValue("reqAmount")); // 申请数量
			Long companyId = logonUser.getCompanyId();

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("wareHouseId", wareHouseId);
			map.put("materalId", materalId);
			map.put("orderType", orderType);
			map.put("specialBatchNo", specialBatchNo);
			map.put("companyId", companyId.toString());
			List<Map<String, Object>> w_List = dao.getPatchNoSelectQuery(map);
			act.setOutData("w_List", w_List);
			act.setOutData("batchNo", batchNo);
			act.setOutData("materalId", materalId);
			act.setOutData("amount", amount);
			act.setOutData("initNo", initNo);
			act.setOutData("reqAmount", reqAmount);
			act.setForword(deinitMyOneUrl);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e, ErrorCodeConstant.QUERY_FAILURE_CODE,
					"订单资源审核批次号选择");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}
	/*
	 * 经销商确认明细
	 */
	public void dealerDeliveryToCheck(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String reqId = request.getParamValue("reqId");
			String orderType = request.getParamValue("orderType");
			Long companyId = GetOemcompanyId.getOemCompanyId(logonUser);
			Map<String, Object> map = dao.getdeliveryMap(reqId);
			OrderAuditDao od = new OrderAuditDao();
			String areaGet = ((BigDecimal) map.get("AREA_ID")).toString();
			List<Map<String, Object>> list = od.getorderResourceReserveDetailList(reqId,orderType,String.valueOf(companyId), areaGet);
			BigDecimal dealerId = (BigDecimal)map.get("BILLING_ORG_ID");// 开票方
			List<Map<String,Object>> discountList = accoutDao.getDiscountAccountInfoByDealerId(dealerId.toString());
			
			// 判断当前经销商是否是订单开票方
			String dealerIds = logonUser.getDealerId();
			String url = deinitList2;
			if(Utility.testString(dealerIds)){
				String[] array = dealerIds.split(",");
				for(int i = 0; i < array.length; i++){
					if(array[i].equals(dealerId.toString())){
						url = deinitList;
					}
				}
			}
			act.setOutData("map", map);
			act.setOutData("list", list);
			act.setOutData("discountList", discountList);
			act.setForword(url);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"经销商确认明细");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	
	/**
	 * 发运指令下达明细查询
	 */
	public void deliveryToQuery(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String reqId =request.getParamValue("reqId");	
			Integer curPage = request.getParamValue("curPage") !=null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps = dao.getDeliveryDetailList(reqId, curPage, 9999);
			act.setOutData("ps", ps);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"发运指令下达查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	/**
	 * 发运确认
	 */
	public void deliverySubmit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try{
			String reqId = request.getParamValue("reqId");
			String checkRemark = request.getParamValue("checkRemark");
			String ver = request.getParamValue("ver");
			//避免重复操作
			int newVer = dao.getBeforVer(reqId);
			if(newVer==Integer.parseInt(ver)){
				String orderType = request.getParamValue("orderType");
				String wid = request.getParamValue("");
				Map<String, Object> map = dao.getdeliveryMap(reqId);
				Long companyId = GetOemcompanyId.getOemCompanyId(logonUser);
				OrderAuditDao od = new OrderAuditDao();
				String areaGet = ((BigDecimal) map.get("AREA_ID")).toString();
				List<Map<String, Object>> list = od.getorderResourceReserveDetailList(reqId,orderType,String.valueOf(companyId),areaGet);
				List<Map<String, Object>> order = dao.getOrderList(reqId);
				
				// 查询是否有财务已驳回的发运单
				TtVsDlvryPO tvdp = new TtVsDlvryPO();
				tvdp.setReqId(new Long(reqId));
				tvdp.setDeliveryStatus(Constant.DELIVERY_STATUS_03);
				List<PO> dlvryList = dao.select(tvdp);
				for(int i=0; i<dlvryList.size(); i++){
					tvdp = (TtVsDlvryPO)dlvryList.get(i);
					Long deliveryId = tvdp.getDeliveryId();
					
					TtVsDlvryDtlPO tvddpo = new TtVsDlvryDtlPO();
					tvddpo.setDeliveryId(deliveryId);
					dao.delete(tvddpo); //删除发运单明细
					
					TtVsDlvryPO tvdpo = new TtVsDlvryPO();
					tvdpo.setDeliveryId(deliveryId);
					dao.delete(tvdpo); //删除发运单
				}
				
				TtVsDlvryPO po = new TtVsDlvryPO();
				po.setDeliveryId(Long.parseLong(SequenceManager.getSequence("")));
				po.setReqId(Long.parseLong(reqId));
				//po.setDeliveryNo(SequenceManager.getSequence("FYDH"));
				po.setDeliveryNo(list.get(0).get("DLVRY_REQ_NO").toString());
				po.setOrderId(Long.parseLong(String.valueOf(map.get("ORDER_ID"))));
				po.setFundType(Long.parseLong(String.valueOf(map.get("FUND_TYPE"))));
				po.setDeliveryType(Integer.parseInt(String.valueOf(map.get("DELIVERY_TYPE"))));
				if(map.get("ADDRESS_ID") != null){
					po.setAddressId(Long.parseLong(String.valueOf(map.get("ADDRESS_ID"))));
				}
				Date date = new Date();
				po.setDeliveryDate(date);
				po.setDeliveryStatus(Constant.DELIVERY_STATUS_01);
				//po.setVer(newVer+1);
				po.setCreateBy(logonUser.getUserId());
				po.setCreateDate(date);
				po.setPriceId(Long.parseLong(String.valueOf(map.get("PRICE_ID"))));
				if(map.get("OTHER_PRICE_REASON") != null){
					po.setOtherPriceReason(String.valueOf(map.get("OTHER_PRICE_REASON")));
				}
				po.setReceiver(Long.parseLong(String.valueOf(map.get("RECEIVER"))));
				if(map.get("LINK_MAN") != null){
					po.setLinkMan(String.valueOf(map.get("LINK_MAN")));
				}
				if(map.get("TEL") != null){
					po.setTel(String.valueOf(map.get("TEL")));
				}
				po.setDiscount(Double.parseDouble(String.valueOf(map.get("DCOUNT"))));
				po.setBillingSide(Long.parseLong(String.valueOf(map.get("BILLING_ORG_ID"))));
				po.setCompanyId(GetOemcompanyId.getOemCompanyId(logonUser));
				po.setWarehouseId(Long.parseLong(String.valueOf(map.get("WAREHOUSE_ID"))));//插入库存表ID
				dao.insert(po);//插入发运表
				
				TtVsReqCheckPO kk = new TtVsReqCheckPO();
				kk.setCheckId(Long.parseLong(SequenceManager.getSequence("")));
				kk.setReqId(po.getReqId());
				kk.setCheckOrgId(logonUser.getOrgId());
				kk.setCheckPositionId(logonUser.getPoseId());
				kk.setCheckUserId(logonUser.getUserId());
				kk.setCheckDate(date);
				kk.setCheckStatus(Constant.CHECK_STATUS_03);
				kk.setCreateBy(logonUser.getUserId());
				kk.setCheckDesc(checkRemark);
				kk.setCreateDate(date);//插入审核记录表
				dao.insert(kk);
				
				TtVsDlvryReqPO tr = new TtVsDlvryReqPO();
				TtVsDlvryReqPO tv = new TtVsDlvryReqPO();
				tr.setReqId(Long.parseLong(reqId));
				tv.setReqExecStatus(Constant.REQ_EXEC_STATUS_02);
				tv.setReqStatus(Constant.ORDER_REQ_STATUS_04);
				tv.setVer(newVer+1);
				tv.setUpdateBy(po.getCreateBy());
				tv.setUpdateDate(po.getCreateDate());
				dao.update(tr, tv);//更新发运申请表
				//向发运申请操作日志表写入日志信息
				ReqLogUtil.creatReqLog(Long.parseLong(reqId), Constant.REQ_LOG_TYPE_04, logonUser.getUserId());
				
				if(list != null && list.size() > 0){
					for(int i=0; i<list.size(); i++){
						TtVsDlvryReqDtlPO vv = new TtVsDlvryReqDtlPO();
						TtVsDlvryReqDtlPO aa = new TtVsDlvryReqDtlPO();
						vv.setDetailId(Long.parseLong(String.valueOf(list.get(i).get("DETAIL_ID"))));
						int damount = 0;
						if(list.get(i).get("RESERVE_AMOUNT") != null){
							damount = Integer.parseInt(String.valueOf(list.get(i).get("RESERVE_AMOUNT")));
						}
						aa.setDeliveryAmount(damount);
						aa.setUpdateBy(po.getCreateBy());
						aa.setUpdateDate(po.getCreateDate());
						dao.update(vv, aa);//更新发运申请明细
						
						TtVsDlvryDtlPO dd = new TtVsDlvryDtlPO();
						dd.setDetailId(Long.parseLong(SequenceManager.getSequence("")));
						dd.setDeliveryId(po.getDeliveryId());
						dd.setReqId(Long.parseLong(reqId));
						dd.setMaterialId(Long.parseLong(String.valueOf(list.get(i).get("MATERIAL_ID"))));
						dd.setReqDtlId(Long.parseLong(String.valueOf(list.get(i).get("DETAIL_ID"))));
						dd.setDeliveryAmount(Integer.parseInt(String.valueOf(list.get(i).get("RESERVE_AMOUNT"))));
						dd.setVer(0);
						dd.setCreateBy(po.getCreateBy());
						dd.setCreateDate(po.getCreateDate());
						dao.insert(dd);
						
						if(order != null && order.size() > 0){
							for(int j=0;j<order.size();j++){
								String orid = String.valueOf(list.get(i).get("ORDER_DETAIL_ID"));
								String odid = String.valueOf(order.get(j).get("ODID"));
								if(orid.equals(odid)){
									TtVsOrderDetailPO bb = new TtVsOrderDetailPO();
									TtVsOrderDetailPO cc = new TtVsOrderDetailPO();
									bb.setDetailId(Long.parseLong(String.valueOf(odid)));
									int ra = 0;
									int da = 0;
									if(list.get(i).get("RESERVE_AMOUNT")!=null){
										ra = Integer.parseInt(String.valueOf(list.get(i).get("RESERVE_AMOUNT")));
									}
									if(order.get(j).get("DELIVERY_AMOUNT")!=null){
										da = Integer.parseInt(String.valueOf(order.get(j).get("DELIVERY_AMOUNT")));
									}
									cc.setDeliveryAmount(ra+da);
									cc.setUpdateBy(po.getCreateBy());
									cc.setUpdateDate(date);
									dao.update(bb, cc);//更新订单明细
								}
							}
						}
					}
				}
				
				// 调用发运存储过程
				List<Object> ins = new LinkedList<Object>();
				ins.add(po.getDeliveryId().toString());

				List<Integer> outs = new LinkedList<Integer>();
				
				dao.callProcedure("P_INSERTDATA_TO_DFS", ins, outs);
				
				act.setOutData("returnValue", "1");
			}else{
				act.setOutData("returnValue", "0");
			}
		  }catch(Exception e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.PUTIN_FAILURE_CODE,"下达发运指令信息");
			logger.error(logonUser,e1);
		 	act.setException(e1);
		  }
	}
	
	/*
	 * 驳回初审
	 */
	public void deliverySubBack(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String reqId = request.getParamValue("reqId");
			String checkRemark = request.getParamValue("checkRemark");
			String ver = request.getParamValue("ver");
			//避免重复操作
			int newVer = dao.getBeforVer(reqId);
			if(newVer==Integer.parseInt(ver)){
				TtVsDlvryReqPO po = new TtVsDlvryReqPO();
				TtVsDlvryReqPO tp = new TtVsDlvryReqPO();
				po.setReqId(Long.parseLong(reqId));
				tp.setReqStatus(Constant.ORDER_REQ_STATUS_05);
				tp.setUpdateBy(logonUser.getUserId());
				tp.setUpdateDate(new Date());
				tp.setVer(new Integer(newVer+1));
				dao.update(po, tp);
				
				TtVsReqCheckPO kk = new TtVsReqCheckPO();
				kk.setCheckId(Long.parseLong(SequenceManager.getSequence("")));
				kk.setReqId(po.getReqId());
				kk.setCheckOrgId(logonUser.getOrgId());
				kk.setCheckPositionId(logonUser.getPoseId());
				kk.setCheckUserId(logonUser.getUserId());
				kk.setCheckDate(tp.getUpdateDate());;
				kk.setCheckStatus(Constant.CHECK_STATUS_04);
				kk.setCheckDesc(checkRemark);
				kk.setCreateBy(logonUser.getUserId());
				kk.setCreateDate(tp.getUpdateDate());//插入审核记录表
				dao.insert(kk);
				
				act.setOutData("returnValue", "1");
			}else{
				act.setOutData("returnValue", "0");
			}
		
		} catch(Exception e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"审核驳回");
			logger.error(logonUser,e1);
		 	act.setException(e1);
		  }
	}
	
	public void queryBatchNumberInit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String materialId =request.getParamValue("materialId");		   		
			//得到仓库列表
			Long companyId=GetOemcompanyId.getOemCompanyId(logonUser);
			List<Map<String, String>> warehouseList = dao.getWarehouseList(companyId);
			act.setOutData("materialId", materialId);
			act.setOutData("warehouseList", warehouseList);
			act.setForword(queryBatchNumberInitURL);
		} catch(Exception e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.PUTIN_FAILURE_CODE,"查询批次号INIT");
			logger.error(logonUser,e1);
		 	act.setException(e1);
		  }
	}
	
	public void queryBatchNumberList(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String materialId = CommonUtils.checkNull(request.getParamValue("materialId"));
			String warehouse_id = CommonUtils.checkNull(request.getParamValue("warehouse_id"));
			Long oemCompanyId=GetOemcompanyId.getOemCompanyId(logonUser);
			Integer curPage = request.getParamValue("curPage") !=null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps = dao.getBatchNumberList(oemCompanyId, materialId, warehouse_id, Constant.PAGE_SIZE, curPage);
			act.setOutData("ps", ps);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	/*
	 * 经销商确认
	 */ 
	public void dealerDeliveryInit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			act.setForword(deinitUrl);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"经销商确认");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void dealerDeliveryQuery(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String dealerId = logonUser.getDealerId();
			Long poseId = logonUser.getPoseId() ;
			Integer curPage = request.getParamValue("curPage") !=null ? Integer.parseInt(request.getParamValue("curPage")) : 1;
			PageResult<Map<String, Object>> ps = dao.getDealerDeliveryList(poseId,dealerId,curPage, Constant.PAGE_SIZE);
			act.setOutData("ps", ps);
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"发运指令下达查询");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 经销商同意操作
	 */
	public void dealerDeliverySubmit(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String reqId = request.getParamValue("reqId");
			Integer reqTotalAmount = new Integer(0);
			
			updateOrderPrice(dao.getLowOrder_CG(reqId)) ; // 结算中心下级经销商同步，更新价格列表
			
			TtVsDlvryReqDtlPO tvdrdp = new TtVsDlvryReqDtlPO();
			tvdrdp.setReqId(new Long(reqId));
			List<PO> dlist = dao.select(tvdrdp);
			for(int i=0; i<dlist.size(); i++){
				tvdrdp = (TtVsDlvryReqDtlPO)dlist.get(i);
				reqTotalAmount += tvdrdp.getReserveAmount();
				
				// 发车申请明细修改
				TtVsDlvryReqDtlPO tvdrdp1 = new TtVsDlvryReqDtlPO();
				tvdrdp1.setDetailId(tvdrdp.getDetailId());
				TtVsDlvryReqDtlPO tvdrdp2 = new TtVsDlvryReqDtlPO();
				tvdrdp2.setReqAmount(tvdrdp.getReserveAmount());
				tvdrdp2.setUpdateBy(logonUser.getUserId());
				tvdrdp2.setUpdateDate(new Date());
				dao.update(tvdrdp1, tvdrdp2);
				
				// 订单明细修改
				TtVsOrderDetailPO tvodp = reportDao.getTtSalesOrderDetail(tvdrdp.getOrderDetailId().toString());
				
				TtVsOrderDetailPO tvodp1 = new TtVsOrderDetailPO();
				tvodp1.setDetailId(tvodp.getDetailId());
				TtVsOrderDetailPO tvodp2 = new TtVsOrderDetailPO();
				tvodp2.setCallAmount(tvodp.getCallAmount() - tvdrdp.getReqAmount() + tvdrdp.getReserveAmount());
				tvodp2.setUpdateBy(logonUser.getUserId());
				tvodp2.setUpdateDate(new Date());
				dao.update(tvodp1, tvodp2);
			}
			
			TtVsDlvryReqPO po = new TtVsDlvryReqPO();
			TtVsDlvryReqPO tp = new TtVsDlvryReqPO();
			po.setReqId(Long.parseLong(reqId));
			tp.setReqStatus(Constant.ORDER_REQ_STATUS_03);
			tp.setReqTotalAmount(reqTotalAmount);
			tp.setUpdateBy(logonUser.getUserId());
			tp.setUpdateDate(new Date());
			dao.update(po, tp);
			
			
			//向发运申请操作日志表写入日志信息
			ReqLogUtil.creatReqLog(new Long(reqId), Constant.REQ_LOG_TYPE_03, logonUser.getUserId());
			
			TtVsDlvryReqPO existsPo = getDlvryReqByReqId(Long.parseLong(reqId));			
			//同步结算中心下级经销商订单
			AccountBalanceDetailDao.getInstance().syncOrderToDFS(existsPo.getOrderId(), true, logonUser.getUserId(), false);
			
			act.setOutData("returnValue", "1");
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"经销商同意");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	private TtVsDlvryReqPO getDlvryReqByReqId(Long reqId){
		TtVsDlvryReqPO po = new TtVsDlvryReqPO();
		po.setReqId(reqId);
		List<PO> list = dao.select(po);
		return list.size() != 0 ? (TtVsDlvryReqPO) list.get(0) : null;
	}
	/*
	 * 经销商取消操作
	 */
	public void dealerDeliverySubBack(){
		AclUserBean logonUser = (AclUserBean)act.getSession().get(Constant.LOGON_USER);
		try {
			String reqId = request.getParamValue("reqId");
			
			updateOrderPrice(dao.getLowOrder_CG(reqId)) ; // 结算中心下级经销商同步，更新价格列表
			
			String orderType = request.getParamValue("orderType");
			TtVsDlvryReqPO po = new TtVsDlvryReqPO();
			TtVsDlvryReqPO tp = new TtVsDlvryReqPO();
			po.setReqId(Long.parseLong(reqId));
			tp.setReqStatus(Constant.ORDER_REQ_STATUS_07);
			tp.setUpdateBy(logonUser.getUserId());
			tp.setUpdateDate(new Date());
			dao.update(po, tp);//更新发运申请表
			
			Map<String, Object> map = dao.getdeliveryInfoMap(reqId);
			Long companyId = GetOemcompanyId.getOemCompanyId(logonUser);
			OrderAuditDao od = new OrderAuditDao();
			String areaGet = ((BigDecimal) map.get("AREA_ID")).toString();
			List<Map<String, Object>> list = od.getorderResourceReserveDetailList(reqId,orderType,String.valueOf(companyId),areaGet);
			
			TtVsOrderPO aa = new TtVsOrderPO();
			TtVsOrderPO bb = new TtVsOrderPO();
			aa.setOrderId(Long.parseLong(String.valueOf(map.get("ORDER_ID"))));
			bb.setOrderStatus(Constant.ORDER_STATUS_06);
			bb.setUpdateBy(logonUser.getUserId());
			bb.setUpdateDate(tp.getUpdateDate());
			dao.update(aa, bb);//更新订单表
			
			if(list!=null&&list.size()>0){
				for(int i=0;i<list.size();i++){
					TtVsOrderResourceReservePO cc = new TtVsOrderResourceReservePO();
					TtVsOrderResourceReservePO dd = new TtVsOrderResourceReservePO();
					cc.setReqDetailId(Long.parseLong(String.valueOf(list.get(i).get("DETAIL_ID"))));
					dd.setReserveStatus(Constant.RESOURCE_RESERVE_STATUS_02);
					dao.update(cc, dd);
				}
			}
			
			/*
			 * 此处为资金回滚 
			 */
			dmsReleasePrice(reqId, logonUser.getUserId().toString());
			
			/*
			 * 此处为资金回滚 
			 
			AccountBalanceDetailDao dao = AccountBalanceDetailDao.getInstance();
			dao.releaseAllFreezeAmountByReqId(reqId, logonUser.getUserId().toString());*/
			//向发运申请操作日志表写入日志信息
			ReqLogUtil.creatReqLog(new Long(reqId), Constant.REQ_LOG_TYPE_03, logonUser.getUserId());
			
			TtVsDlvryReqPO existsPo = getDlvryReqByReqId(Long.parseLong(reqId));			
			//同步下级经销商订单
			AccountBalanceDetailDao.getInstance().syncOrderToDFS(existsPo.getOrderId(), true, logonUser.getUserId(), true);
			act.setOutData("returnValue", "1");
		} catch(RuntimeException e) {
			BizException e1 = new BizException(act,e,ErrorCodeConstant.PUTIN_FAILURE_CODE,e.getMessage());
			logger.error(logonUser,e1);
			act.setException(e);
		} catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.SPECIAL_MEG,"经销商取消");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	public void updateOrderPrice(Map<String, Object> map) {
		String orderId = map.get("OLD_ORDER_ID").toString() ;
		
		if("".equals(orderId) || "-1".equals(orderId)) {
			return ;
		}

		String dealerId = map.get("ORDER_ORG_ID").toString() ;

		String priceId = dao.getNewPrice(dealerId) ;

		if(!"".equals(priceId)) {
			dao.updateOrderPrice(orderId, priceId) ;
		}
	}
}
